package com.naizhuai.ui.msgmanager;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.util.DiffUtil;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.naizhuai.Model.AccountHelper;
import com.naizhuai.R;
import com.naizhuai.network.NetWorkObserver;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.components.MultStateView;
import com.naizhuai.ui.components.swipeback.SwipeBackActivity;
import com.naizhuai.ui.entity.management.ApplyID;
import com.naizhuai.ui.entity.management.RequestJoinMessageBean;
import com.naizhuai.ui.management.presenter.CompanyManageDataApiStore;
import com.naizhuai.ui.management.presenter.CompanyManageDataApiStoreIml;
import com.naizhuai.util.ConstantsState;
import com.naizhuai.util.DialogUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class PersonExamineActivity extends SwipeBackActivity implements PersonExamineaAdapter.PassRejectCallBack {
    public static void start(Context context) {
        Intent intent = new Intent(context, PersonExamineActivity.class);
        if (context instanceof BaseActivity){
            ((BaseActivity) context).startActivityTransition(intent);
        }else {
            context.startActivity(intent);
        }
    }
    @BindView(R.id.multstateView)
    MultStateView multstateView;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.chosen_select)
    ImageView chosenSelect;
    @BindView(R.id.selectall)
    TextView selectall;
    @BindView(R.id.previous)
    ImageView previous;
    @BindView(R.id.page)
    TextView pageNum;
    @BindView(R.id.next)
    ImageView next;
    @BindView(R.id.examine_list)
    RecyclerView examineList;
    @BindView(R.id.btn_pass)
    Button btnPass;
    PersonExamineaAdapter mExamineaAdapter;
    private CompanyManageDataApiStore mManageDataApiStore;
    private List<RequestJoinMessageBean> mOldDatas;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        toolbar.setNavigationOnClickListener(v -> finish());
        examineList.setLayoutManager(new LinearLayoutManager(this));
        examineList.setItemAnimator(new DefaultItemAnimator());
        examineList.setAdapter(mExamineaAdapter = new PersonExamineaAdapter(this));
        mExamineaAdapter.getCheckSubject().subscribe(s -> handleBtnState());
        initData();
        multstateView.setOnRetryClickListener(v -> requestPersonCheck(countPage));
    }

    private void handleBtnState() {
        if (mExamineaAdapter.getSelectedCount() > 0){
            btnPass.setEnabled(true);
        } else {
            btnPass.setEnabled(false);
        }
    }

    private int countPage = 1;

    private void initData() {
        if (mManageDataApiStore == null) {
            mManageDataApiStore = CompanyManageDataApiStoreIml.getInstance();
        }
        requestPersonCheck(countPage);
    }

    private void requestPersonCheck(int page) {
        chosenSelect.setSelected(false);
        pageNum.setText(String.valueOf(page));
        showWaitDiaLog();
        mManageDataApiStore.getRequestMessageList(AccountHelper.getComPanyid(), page, 10)
                .subscribe(new NetWorkObserver<List<RequestJoinMessageBean>>() {
                    @Override
                    protected void onFail(String errormsg) {
                        hideWaitDialog();
                        shortToast(errormsg);
                    }

                    @Override
                    protected void onSuccess(List<RequestJoinMessageBean> result) {
                        hideWaitDialog();
                        if (mOldDatas == null) {
                            if (result.size() > 0) {
                                mOldDatas = result;
                                mExamineaAdapter.setResult(mOldDatas);
                                mExamineaAdapter.notifyDataSetChanged();
                                multstateView.showView(MultStateView.STATUS_CONTENT);
                            } else {
                                multstateView.showView(MultStateView.STATUS_NOMSG);
                            }
                        } else {
                            DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new DiffCallBack(mOldDatas, result), true);
                            diffResult.dispatchUpdatesTo(mExamineaAdapter);
                            mExamineaAdapter.setResult(result);
                            mOldDatas = result;
                        }
                    }
                });
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_person_examine;
    }


    @OnClick(R.id.chosen_select)
    public void onChosenSelectClicked() {
        //把所有的都变成true
        if (chosenSelect.isSelected()) {
            //false
            mExamineaAdapter.changeSelect(false);
        } else {
            //true
            mExamineaAdapter.changeSelect(true);
        }
        handleBtnState();
        chosenSelect.setSelected(!chosenSelect.isSelected());
    }

    @OnClick(R.id.previous)
    public void onPreviousClicked() {
        if (countPage == 1) {
            shortToast(getString(R.string.current_alreaday_first_page));
            return;
        }
        requestPersonCheck(--countPage);
    }

    @OnClick(R.id.next)
    public void onNextClicked() {
        requestPersonCheck(++countPage);
    }

    @OnClick(R.id.btn_pass)
    public void onAllPassClicked() {
        List<ApplyID> stringList = mExamineaAdapter.getSelected();
        handleApply("pass", stringList);
    }

    @Override
    public void pass(String applyId) {
        ArrayList<ApplyID> arrayList = new ArrayList<>(1);
        arrayList.add(new ApplyID(applyId));
        DialogUtils.showSureDialog(this, getString(R.string.sure_agree_apply), v ->
                handleApply("pass", arrayList));
    }

    @Override
    public void reject(String applyId) {
        ArrayList<ApplyID> arrayList = new ArrayList<>(1);
        arrayList.add(new ApplyID(applyId));
        DialogUtils.showSureDialog(this, getString(R.string.sure_reject_apply), v ->
                handleApply("failure", arrayList));
    }

    private void handleApply(String applyRes, List<ApplyID> list) {
        showWaitDiaLog();
        if (list != null) {
            mManageDataApiStore.handleApply(applyRes, new Gson().toJson(list))
                    .subscribe(new NetWorkObserver<String>() {
                        @Override
                        protected void onFail(String errormsg) {
                            hideWaitDialog();
                            shortToast(errormsg);
                        }

                        @Override
                        protected void onSuccess(String result) {
                            hideWaitDialog();
                            if (ConstantsState.isResultOk(result)) {
                                shortToast(getString(R.string.action_ok));
                                requestPersonCheck(countPage);
                            } else {
                                shortToast(getString(R.string.action_fail));
                            }
                        }
                    });
        }
    }


//    private void againRequestPage(int page) {
//        showWaitDiaLog();
//        mManageDataApiStore.getRequestMessageList(AccountHelper.getComPanyid(), page, 10)
//                .subscribe(new NetWorkObserver<List<RequestJoinMessageBean>>() {
//                    @Override
//                    protected void onFail(String errormsg) {
//                        hideWaitDialog();
//                        shortToast(errormsg);
//                    }
//
//                    @Override
//                    protected void onSuccess(List<RequestJoinMessageBean> result) {
//                        hideWaitDialog();
//                        mExamineaAdapter.setResult(result);
//                        mExamineaAdapter.notifyDataSetChanged();
//                    }
//                });
//    }

    class DiffCallBack extends DiffUtil.Callback {
        private List<RequestJoinMessageBean> mOldDatas, mNewDatas;

        public DiffCallBack(List<RequestJoinMessageBean> mOldDatas,
                            List<RequestJoinMessageBean> mNewDatas) {
            this.mOldDatas = mOldDatas;
            this.mNewDatas = mNewDatas;
        }

        @Override
        public int getOldListSize() {
            return mOldDatas != null ? mOldDatas.size() : 0;
        }

        @Override
        public int getNewListSize() {
            return mNewDatas != null ? mNewDatas.size() : 0;
        }

        @Override
        public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
            return mOldDatas.get(oldItemPosition).getPhoneNumber()
                    .equals(mNewDatas.get(newItemPosition).getPhoneNumber());
        }

        @Override
        public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
            return false;
        }
    }
}
